
var roleUpWin;
 
 var roleUpNameField=new Ext.form.TextField({
		labelAlign:'right',
		allowBlank:false,
		fieldLabel: '角色名称',
		width:200
});
	
var roleUpRemarkArea=new Ext.form.TextArea({
		labelAlign:'right',
		fieldLabel: '备注信息',
		width:200
});
	
 function showRoleUpForm(id,sname,sremark,nisValid) {
        var roleUpform = new Ext.FormPanel({
            border: false,
            items: [roleUpNameField, roleUpRemarkArea],
            buttons: [{
                text: '修 改',
                handler: function() {
                	
                	if(!roleUpNameField.validate()){
						return ;
					}
                	Ext.Ajax.request({
						url:'upRole.do',
						method:'POST',
						params : {
						   'nrightId':id,
						   'nisValid':nisValid,
		                   'sname' : roleUpNameField.getValue(), 
		                   'sremark' : roleUpRemarkArea.getValue() 
		                }, 
		  				success: function (response) {
		  					if(response.responseText=='true'){
	                            Ext.MessageBox.alert('信息!', '修改成功!');
	                            roleUpform.getForm().reset();
	                            roleUpWin.hide();
	                            roleGridStore.reload();
		  					}
		  					else{
		  						Ext.Msg.alert("Error","修改角色失败！"); 
		  					}
		              	}, 
		  				failure: function (response) {
		                    Ext.Msg.alert("Error","错误"); 
		            	}
					});
                }
            },{
                text: '返 回',
                handler: function() {
                	roleUpform.getForm().reset();
                	roleUpWin.hide();
                }
            }]
        });

     roleUpWin = new Ext.Window({
            title: '修改角色',
            closeAction: 'hide',
            width: 400,
            height: 220,
            minHeight: 200,
            layout: 'fit',
            resizable: true,
            modal: true,
            items: roleUpform,
            listeners :{
            	close:function(){
            		roleUpform.getForm().reset();
            	}
            }
        });
        
    roleUpWin.show();
    roleUpWin.setTitle('修改角色:'+sname);
    roleUpNameField.setValue(sname);
    roleUpRemarkArea.setValue(sremark);
}
    
function roleGridColumnsRenderUplink(id,sname,sremark,nisValid){
		showRoleUpForm(id,sname,sremark,nisValid);
}

function roleGridColumnsRenderDellink(id,sname){
	
	Ext.MessageBox.confirm('信息', '是否确认删除 角色： '+sname+'?', function(btn){
		if(btn=='yes'){
				Ext.Ajax.request({
					url:'delRole.do',
					method:'POST',
					params : {
					   ids:id
		            }, 
					success: function (response) {
						if(response.responseText=='true'){
		                    Ext.MessageBox.alert('信息!', '删除成功!');
		                    roleGridStore.reload();
						}
						else{
							Ext.Msg.alert("Error","删除角色失败！"); 
						}
		          	}, 
					failure: function (response) {
		                Ext.Msg.alert("Error","错误"); 
		        	}
				});
		}
		
	});
		
}

function roleGridColumnsRenderRolelink(id,sName){
	showRolePermissForm(id,sName);
}

function roleGridColumnsRenderRoleMlink(id,sName){
	showRolePermissMForm(id,sName);
}

var rolePermiss;

function showRolePermissForm(id,sName){
		 
	var rolePermissTree = new Ext.tree.TreePanel({
			header:false,
	        frame: true,
	        rootVisible:false,
	        border:false,
	        collapsible: true,
	        autoScroll:true,
	        root: {
	        	nodeType: 'async',
	            text: 'Ext JS',
	            draggable: false,
	            id: 'src'
	        },
	        listeners: {
	            checkchange: function(n, checked){
	            	
	            	//如果有父节点 则改变父节点的选中状态
	            	if(n.parentNode.attributes.checked==true||n.parentNode.attributes.checked==false){
	            		var i=0;
			            n.parentNode.eachChild(function(node){
			    			if(node.attributes.checked==true){
			    				i++;
							}
						});
						if(i==0){
							n.parentNode.ui.toggleCheck(false);
						}else{
							n.parentNode.ui.toggleCheck(true);
						}
						i=null;
	            	}
			    }
			},
	        dataUrl:'selectRolePermiss.do?nRoleId='+id
	 });
	
	  var rolePermissTreeform = new Ext.FormPanel({
            border: false,
            frame:true,
            layout:'fit',
            items: [rolePermissTree],
            buttons: [{
                text: '修 改',
                handler: function() {
					var rolePTreeRootNode=rolePermissTree.getRootNode();
					var nNavTrees=new Array();
					
					//递归所有节点 得到所有选中的节点
					eachNodes(rolePTreeRootNode);
					
				    function eachNodes(nodes){
				    	if(nodes.eachChild){
				    		var nNavTree='';
				    		nodes.eachChild(function(node){
				    			if(node.attributes.checked==true){
				    				nNavTrees.push(node.attributes.nNavTreeId);
				    			}
				    			eachNodes(node);
							})
				    	}
				    }
				    //去除重复的值
				    Ext.unique(nNavTrees);

				    if(nNavTrees==''){
				    	return;
				    }
				    Ext.Ajax.request({
						url:'upRolePermiss.do',
						method:'POST',
						params : {
		                   'nNavTrees' : nNavTrees.toString(), 
		                   'nRoleId' : id 
		                }, 
		  				success: function (response) {
		  					if(response.responseText=='true'){
	                            Ext.MessageBox.alert('信息!', '修改成功!');
	                            rolePermisswin.hide();
		  					}
		  					else{
		  						Ext.Msg.alert("Error","添加角色失败！"); 
		  					}
		  					nNavTrees=null;
		              	}, 
		  				failure: function (response) {
		  					nNavTrees=null;
		                    Ext.Msg.alert("Error","错误"); 
		            	}
					});
					
				}},{
                text: '返 回',
                handler: function() {
                	rolePermisswin.hide();
                }
            }]
        });

	rolePermisswin = new Ext.Window({
	    title: sName+':角色菜单',
	    closeAction: 'hide',
	    width: 350,
	    border:false,
	    height: 500,
	    layout: 'fit',
	    resizable: true,
	    modal: true,
	    items:[rolePermissTreeform]
	});
	rolePermisswin.show();
}

//通过改变checkbox修改读写权限的json值
	 function nRWcheckboxup(checked,index){
//		var rpmmstore=rolePermissMgrid.getStore();
		if(checked==true){
			rolePermissMgrid.getStore().data.items[index].json.nRW=2;
		}else{
			rolePermissMgrid.getStore().data.items[index].json.nRW=1;
		}
	}
var rolePermissMwin;
function showRolePermissMForm(id,sName){
		 
	  rolePermissMgrid = new Ext.grid.GridPanel({
			disableSelection: true,
			border:false,
			stripeRows:true,
			frame:true,
			loadMask :{msg:"数据加载中，请稍等..."},
			layout:'fit',
			viewConfig:{
				forceFit: true,
				scrollOffset:0
			},
	        cm:new Ext.grid.ColumnModel([
	        	new Ext.grid.RowNumberer(),
	            {header: "菜单名称", width:50, dataIndex: 'sName', sortable: true},
	            {header: "写入权限", width:50, dataIndex: 'nRW',align:'center', sortable: true,
	            	renderer:function(value,record,aa,index,ind){
	            		if(value==1){
	            			return '<input type="checkbox" onclick="nRWcheckboxup(this.checked,'+index+')" value="'+aa.json.nNavTreeId+'">';
	            		}else{
	            			return '<input type="checkbox" checked="checked" value="'+aa.json.nNavTreeId+'" onclick="nRWcheckboxup(this.checked,'+index+')">';
	            		}
	            	}
	            }
	        ]),
	        store: new Ext.data.Store({
		        autoLoad: true,
		        proxy : new Ext.data.HttpProxy({
		            url: 'selectRoleMPermiss.do'
		        }),
		        baseParams:{'nRoleId': id},
		        reader:new Ext.data.JsonReader({},[
		            {name: 'sName',mapping:'sName', type: 'string'},
		        	{name: 'nRW',mapping:'nRW',   type: 'int'}
		        ])    
		    })
	 });
	
	  var rolePermissMform = new Ext.FormPanel({
            border: false,
            frame:true,
            layout:'fit',
            items: [rolePermissMgrid],
            buttons: [{
                text: '修 改',
                handler: function() {
                	
                	var rpmmstoreup=rolePermissMgrid.getStore();
                	
                	var permissRws=new Array();
                	
                	for (var i = 0; i < rpmmstoreup.data.items.length; i++) {
                		
                		permissRws.push(rpmmstoreup.data.items[i].json.nNavTreeId+'@'+rpmmstoreup.data.items[i].json.nRW);
                	}
                	
				    Ext.Ajax.request({
						url:'updateRoleMPermiss.do',
						method:'POST',
						params : {
		                   'nRoleId' : id, 
		                   'permissRws' : permissRws.toString() 
		                }, 
		  				success: function (response) {
		  					if(response.responseText=='true'){
	                            Ext.MessageBox.alert('信息!', '修改成功!');
	                            rolePermissMwin.hide();
		  					}
		  					else{
		  						Ext.Msg.alert("Error","菜单权限修改失败！"); 
		  					}
		              	}, 
		  				failure: function (response) {
		                    Ext.Msg.alert("Error","错误"); 
		            	}
					});
					
				}},{
                text: '返 回',
                handler: function() {
                	rolePermissMwin.hide();
                }
            }]
        });

	rolePermissMwin = new Ext.Window({
	    title: sName+':菜单权限',
	    closeAction: 'hide',
	    width: 300,
	    border:false,
	    height: 399,
	    layout: 'fit',
	    resizable: true,
	    modal: true,
	    items:[rolePermissMform]
	});
	rolePermissMwin.show();
}

Ext.onReady(function(){
	roleiswriteidb= Ext.get('roleiswriteid').getValue()==1?true:false;
	var roleNameField=new Ext.form.TextField({
		fieldLabel:'角色名称',
		labelAlign:'right'
	});
	
	var roleSearchBtn=new Ext.Button({
		text:'查询',
		handler:function(){
			roleGridStore.load({
				params : {
					start : 0,
					limit : 20,
					'sName':roleNameField.getValue()
				}
			});
		}
	});
	

	var roleSearch=new Ext.Panel({
		height:50,
		region:'north',
		layout:'column',
		frame: true,
		border:false,
		bodyBorder:false,
		items:[
			{columnWidth:.38,layout:'form',labelAlign:'right',items:[roleNameField]},
			{columnWidth:.2,layout:'form',labelAlign:'right',items:[roleSearchBtn]}
			]		
	});
	
    roleGridStore = new Ext.data.Store({
        autoLoad: false,
        proxy : new Ext.data.HttpProxy({
            url: 'searchRole.do'
        }),
        baseParams:{sName: roleNameField.getValue()},
        reader:new Ext.data.JsonReader({
             totalProperty: 'totalSize',
             root:'list'
        },[
            {name: 'nrightId',mapping:'nrightId', type: 'int'},
        	{name: 'nisValid',mapping:'nisValid',   type: 'int'},
        	{name: 'sname',mapping:'sname', type: 'string'},
        	{name: 'sremark',mapping:'sremark', type: 'string'}
        ])      
    });

    var roleAddWin;
    roleAddBtn =new Ext.Button({
		text:'添加角色',
		hidden:roleiswriteidb,
		handler:function(){
			showRoleAddForm();
		}
	});
	
	var roleAddNameField=new Ext.form.TextField({
		labelAlign:'right',
		allowBlank:false,
		width:200,
		fieldLabel: '角色名称'
	});
	
	var roleAddRemarkArea=new Ext.form.TextArea({
		labelAlign:'right',
		fieldLabel: '备注信息',
		width:200
	});
	
     function showRoleAddForm() {
        if (!roleAddWin) {
            var roleAddform = new Ext.FormPanel({
                border: false,
                items: [roleAddNameField,roleAddRemarkArea],
                buttons: [{
                    text: '确 认',
                    handler: function() {
                    	
                    	if(!roleAddNameField.validate()){
                    		return ;
                    	}
                    	Ext.Ajax.request({
							url:'addRole.do',
							method:'POST',
							params : {
			                   sname : roleAddNameField.getValue(), 
			                   sremark : roleAddRemarkArea.getValue() 
			                }, 
			  				success: function (response) {

			  					if(response.responseText=='true'){
		                            Ext.MessageBox.alert('信息!', '添加成功!');
		                            roleAddform.getForm().reset();
		                            roleAddWin.hide();
		                            roleGridStore.reload();
			  					}
			  					else{
			  						Ext.Msg.alert("Error","添加角色失败！"); 
			  					}
			              	}, 
			  				failure: function (response) {
			                    Ext.Msg.alert("Error","错误"); 
			            	}
						});
                    }
                },{
                    text: '返 回',
                    handler: function() {
                    	roleAddform.getForm().reset();
                    	roleAddWin.hide();
                    }
                }]
            });

            roleAddWin =new Ext.Window({
                title: '添加角色',
                closeAction: 'hide',
                width: 400,
                height: 220,
                minHeight: 200,
                layout: 'fit',
                resizable: true,
                modal: true,
                items: roleAddform,
                listeners :{
	            	close:function(){
	            		roleAddform.getForm().reset();
	            	}
            }
            });
        }
        roleAddWin.show();
    }
    var roleGridBar=new Ext.PagingToolbar({
		store: roleGridStore,
		displayInfo: true,
		pageSize:20,
		displayMsg : '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
		emptyMsg: "没有记录可以显示",
		beforePageText:'当前页码',
		afterPageText:'共{0}页', 
		firstText:'第一页', 
		prevText:'上一页', 
		nextText:'下一页', 
		lastText:'最后一页', 
		refreshText:'刷新当前页',
		items:['-', roleAddBtn]
     });

    roleGridColumnsRenderEdit=function(value, cellmeta, record, rowIndex, columnIndex, store){
    	var roleGridCrHtml='';
    	
    	if(roleiswriteidb==false){
    		roleGridCrHtml='<a onclick="roleGridColumnsRenderUplink('+record.data.nrightId+',\''+record.data.sname+'\',\''+record.data.sremark+'\','+record.data.nisValid+')" href="javascript:void(0)">修改</a>';
			roleGridCrHtml+='<a style="margin-left:20px;margin-right:20px" onclick="roleGridColumnsRenderDellink('+record.data.nrightId+',\''+record.data.sname+'\')" href="javascript:void(0)">删除</a>';		
			roleGridCrHtml+='<a style="margin-right:20px" onclick="roleGridColumnsRenderRolelink('+record.data.nrightId+',\''+record.data.sname+'\')" href="javascript:void(0)">菜单</a>';
			roleGridCrHtml+='<a onclick="roleGridColumnsRenderRoleMlink('+record.data.nrightId+',\''+record.data.sname+'\')" href="javascript:void(0)">菜单权限</a>';
    	}
		return roleGridCrHtml;
	};
	
	roleGrid = new Ext.grid.GridPanel({
        store: roleGridStore,
        region:'center',
        bodyBorder:false,
		disableSelection: true,
		border:false,
		frame:true,
		loadMask :{msg:"数据加载中，请稍等..."},
		layout:'fit',
		viewConfig:{
			forceFit: true,
			scrollOffset:0
		},
        cm:new Ext.grid.ColumnModel([
        	new Ext.grid.RowNumberer(),
            {header: "角色标识", width:50, dataIndex: 'nrightId', sortable: true},
            {header: "角色名称", flex: 2, dataIndex: 'sname', sortable: true},
            {header: "备注信息",flex: 3, dataIndex: 'sremark', sortable: true},
            {header: "是否有效", width:50, dataIndex: 'nisValid', sortable: true,
            	renderer:function(value){
            		if (value == 1) {
			            return '有效';
			        }else{
			        	return '无效';
			        }
            	}
            },
            {header: "操作", width:150,align:'center',sortable: true,renderer:roleGridColumnsRenderEdit}
        ]),
        bbar: roleGridBar
    });
    
    var roleMainPanel =new Ext.Viewport({
		layout:'border',
		renderTo:'roleDIV',
		id:'roleMainPanel',
		items:[roleGrid,roleSearch],
		listeners: {
	        'resize': function(viewport,adjWidth,adjHeight,rawWidth,rawHeight)  {
	          	Ext.getCmp("roleMainPanel").setHeight((document.body.clientHeight - 290) * 0.67);  
			}
    	}
	});
})